<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="隐患名称" v-bind="validateInfos.dangerName">
            <a-textarea v-model:value="formData.dangerName" :rows="4" placeholder="请输入隐患名称" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="隐患描述" v-bind="validateInfos.dangerDesc">
            <a-textarea v-model:value="formData.dangerDesc" :rows="4" placeholder="请输入隐患描述" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="隐患产生原因" v-bind="validateInfos.dangerReason">
            <a-textarea v-model:value="formData.dangerReason" :rows="4" placeholder="请输入隐患产生原因" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="隐患等级" v-bind="validateInfos.dangerLevel">
            <j-dict-select-tag type='radio' v-model:value="formData.dangerLevel" dictCode="dangerLevel" placeholder="请选择隐患等级" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="隐患来源" v-bind="validateInfos.dangerSrc">
            <j-dict-select-tag v-model:value="formData.dangerSrc" dictCode="dangerSrc" placeholder="请选择隐患来源" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="隐患治理类型" v-bind="validateInfos.dangerManageType">
            <j-dict-select-tag type='radio' v-model:value="formData.dangerManageType" dictCode="dangerManageType" placeholder="请选择隐患治理类型" :disabled="disabled" @change="changeDangerManageType"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属装置" v-bind="validateInfos.riskDeviceId">
            <j-dict-select-tag v-model:value="formData.riskDeviceId" dictCode="tb_base_risk_device,name,id" placeholder="请选择所属装置" :disabled="disabled" @change="changeDeviceId"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属单元" v-bind="validateInfos.riskUnitId">
            <j-dict-select-tag v-model:value="formData.riskUnitId" :dictCode="argument.unitDictCode" placeholder="请选择所属单元" :disabled="argument.riskUnitFlag"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="资金" v-bind="validateInfos.cost">
            <a-input-number v-model:value="formData.cost" placeholder="请输入资金" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.dangerManageType == '1'">
          <a-form-item label="隐患治理期限" v-bind="validateInfos.dangerManageDeadline">
            <a-date-picker placeholder="请选择隐患治理期限"  v-model:value="formData.dangerManageDeadline" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="隐患状态" v-bind="validateInfos.dangerState">
            <j-dict-select-tag v-model:value="formData.dangerState" dictCode="dangerState" placeholder="请选择隐患状态" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="隐患类型" v-bind="validateInfos.hazardDangerType">
            <j-dict-select-tag v-model:value="formData.hazardDangerType" dictCode="hazardDangerType" placeholder="请选择隐患类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="登记人姓名" v-bind="validateInfos.registrant">
            <j-select-user v-model:value="formData.registrant" disabled="true"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="控制措施" v-bind="validateInfos.controlMeasures">
            <a-textarea v-model:value="formData.controlMeasures" :rows="4" placeholder="请输入控制措施" :disabled="disabled"/>
            <!-- <a-input v-model:value="formData.controlMeasures" placeholder="请输入控制措施" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="管控措施" v-bind="validateInfos.riskMeasureId">
            <j-search-select v-model:value="formData.riskMeasureId" dict="tb_base_control_measures,risk_measure_desc,id" :disabled="disabled" />
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="12">
          <a-form-item label="登记时间" v-bind="validateInfos.registTime">
            <a-date-picker placeholder="请选择登记时间"  v-model:value="formData.registTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" disabled="true"/>
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="整改人" v-bind="validateInfos.liablePerson">
            <j-select-user v-model:value="formData.liablePerson" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="验收人" v-bind="validateInfos.checkAcceptPerson">
            <j-select-user v-model:value="formData.checkAcceptPerson" :disabled="argument.checkAcceptFlag" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="图片" v-bind="validateInfos.img">
            <j-image-upload  v-model:value="formData.img" :disabled="disabled"></j-image-upload>
          </a-form-item>
        </a-col>
        
        <a-divider>专项检查信息</a-divider>
        <a-col :span="12">
          <a-form-item label="所属任务" v-bind="validateInfos.taskId">
            <j-dict-select-tag v-model:value="formData.taskId" dictCode="tb_base_check_task,task_name,id" placeholder="请选择所属任务" :disabled="disabled" @change="changeTask"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="检查类型" v-bind="validateInfos.checkType">
            <j-dict-select-tag v-model:value="formData.checkType" dictCode="baseCheckType" placeholder="请选择检查类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.taskId !=null && formData.taskId != ''">
          <a-form-item label="检查项" v-bind="validateInfos.checkItemId">
            <j-dict-select-tag v-model:value="formData.checkItemId" :dictCode="argument.checkItemCode" placeholder="请选择检查项" :disabled="disabled" @change="changeCheckItem"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="罚款金额" v-bind="validateInfos.checkPay">
            <a-input-number v-model:value="formData.checkPay" placeholder="请输入罚款金额" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="危害类型" v-bind="validateInfos.harmType">
            <j-dict-select-tag v-model:value="formData.harmType" dictCode="harmType" placeholder="请选择危害类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.checkItemId !=null && formData.checkItemId != ''">
          <a-form-item label="检查项评分细则" v-bind="validateInfos.checkScoreId">
            <j-dict-select-tag v-model:value="formData.checkScoreId" :dictCode="argument.checkScoreCode" placeholder="请选择检查项评分细则" :disabled="disabled"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSelectUserByDept from '/@/components/Form/src/jeecg/components/JSelectUserByDept.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../TbBaseDangerInvestigation.api';
  import { Form } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { useUserStore } from '/@/store/modules/user';
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    riskMeasureId: '',   
    dangerName: '',   
    dangerLevel: '',   
    dangerSrc: '',   
    dangerManageType: '',   
    dangerDesc: '',   
    dangerReason: '',   
    controlMeasures: '',   
    cost: undefined,
    dangerManageDeadline: '',   
    dangerState: '',   
    hazardDangerType: '',   
    registrant: '',   
    registTime: '',  
    liablePerson: '',   
    img: '',   
    riskDeviceId: '',   
    riskUnitId: '',   
    hazardCategory: '',  
    taskId: '',
    checkType: '',
    checkItemId: '',
    checkScoreId: '',
    checkPay: '',
    harmType: '',
    dangerId: '',
    baseCheckDangerId: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    dangerName: [{ required: true, message: '请输入隐患名称!'},],
    dangerLevel: [{ required: true, message: '请输入隐患等级!'},],
    dangerSrc: [{ required: true, message: '请输入隐患来源!'},],
    dangerManageType: [{ required: true, message: '请输入隐患治理类型!'},],
    riskDeviceId: [{ required: true, message: '请输入所属装置!'},],
    riskUnitId: [{ required: true, message: '请输入所属单元!'},],
    dangerDesc: [{ required: true, message: '请输入隐患描述!'},],
    hazardDangerType: [{ required: true, message: '请输入隐患类型!'},],
    harmType: [{ required: true, message: '请输入危害类型!'},],
    checkType: [{ required: true, message: '请输入检查类型!'},],
    checkItemId: [{ required: true, message: '请输入检查项!'},],
    checkScoreId: [{ required: true, message: '请输入检查项评分细则!'},],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });
  
  const userStore = useUserStore();
  const argument = reactive({
    unitDictCode: "tb_base_risk_unit,risk_unit_name,id",
    checkScoreCode: "tb_base_check_score,deduct_illustrate,id",
    checkItemCode: "tb_base_check_item,check_content,id",
    checkAcceptFlag: false,
    riskUnitFlag: true
  })

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({
      registrant: userStore.getUserInfo.username,
      registTime: dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss')
    });
  }

  /**
   * 编辑
   */
  function edit(record) {
    console.log("----record---------"+JSON.stringify(record))
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
      console.log("----formData--------"+JSON.stringify(formData))
    });
  }
  
  function changeDeviceId(id) {
    if(id){
      formData.riskUnitId = null;
      argument.riskUnitFlag = false;
    }else{
      argument.riskUnitFlag = true;
    }
    argument.unitDictCode = "tb_base_risk_unit,risk_unit_name,id,device_id='"+id+"'"
  }
  
  function changeDangerManageType(value){
    /* 0标识即查即改，1标识期限整改*/
    if(value === '0'){
      formData.dangerState = "9"
      formData.liablePerson = userStore.getUserInfo.username
      formData.checkAcceptPerson = userStore.getUserInfo.username
      formData.checkAcceptTime = dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss');
      argument.checkAcceptFlag = true;
    }else if(value === '1'){
      formData.dangerState = "0"
      formData.liablePerson = null
      formData.checkAcceptPerson = null
      formData.checkAcceptTime  = null
      argument.checkAcceptFlag = false;
    }
  }
  
  function changeCheckItem(id){
    formData.checkScoreId = null;
    argument.checkScoreCode = "tb_base_check_score,deduct_illustrate,id,check_item_id='"+id+"'"
  }
  function changeTask(id){
    formData.checkItemId = null;
    formData.checkScoreId = null;
    argument.checkItemCode = "tb_base_check_item,check_content,id,task_id='"+id+"'"
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    
    console.log("===formData========"+JSON.stringify(formData))
    /* 组装隐患记录表数据*/
    let baseDangerInvestigationReocrdList = [];
    let BaseDangerInvestigationReocrd ={
      governorTime: formData.checkAcceptTime,
      governor: formData.liablePerson,
      status: formData.dangerState,
      img: formData.img
    }
    baseDangerInvestigationReocrdList.push(BaseDangerInvestigationReocrd);
    formData.baseDangerInvestigationReocrdList = baseDangerInvestigationReocrdList
    
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
    
    argument,
    changeDeviceId,
    changeDangerManageType,
    changeCheckItem,
    changeTask,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
